package com.bauer.os.frame.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.bauer.os.frame.common.BisException;
import com.bauer.os.frame.domain.po.SysUser;
import com.bauer.os.frame.service.SysUserService;

public class UserRealm extends AuthorizingRealm {

	@Autowired
	private SysUserService sysUserService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SysUser user = sysUserService.findUserByName(username);
		if(user==null){
			throw new BisException();
		}
		SimpleAuthorizationInfo authorizatonInfo = new SimpleAuthorizationInfo();
		return authorizatonInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		SysUser user = sysUserService.findUserByName(username);
		if (user == null) {
			throw new BisException();
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(), // 用户名
				user.getPassword(), // 密码
				ByteSource.Util.bytes(user.getName()), // salt=username+salt
				getName() // realm name
		);
		return authenticationInfo;
	}

}
